import React from 'react'
import { Fragment } from 'react'
import AppBar from '../../components/AppBar';
import ReceiverInfo from '../../pages/customer/ReceiverInfo';
import { info } from '../../api/customer'
import { OrderPanel } from '../../components/OrderItem'
import { submitOrder } from '../../api/customer'

export class ConfirmOrder extends React.Component {
    constructor(props) {
        super(props)

        let cart;
        let shop;

        try {
            cart = this.props.location.query.cart;
            shop = this.props.location.query.shop;
        } catch (error) {

        }

        if (!cart) {
            cart = JSON.parse(localStorage.getItem('cart-to-submit'))
        } else {
            localStorage.setItem('cart-to-submit', JSON.stringify(cart))
        }

        if (!shop) {
            shop = JSON.parse(localStorage.getItem('shop-to-submit'))
        } else {
            localStorage.setItem('shop-to-submit', JSON.stringify(shop))
        }

        this.state = {
            receiver: {
                loc: '',
                name: '',
                phone: '',
            },
            cart: cart,
            shop: shop
        }

        this.handleSubmit = this.handleSubmit.bind(this)
    }

    componentDidMount() {
        info((result) => {
            if (result) {
                this.setState({
                    receiver: {
                        loc: JSON.parse(result.receiveInfo)[0].location,
                        name: JSON.parse(result.receiveInfo)[0].rname,
                        phone: JSON.parse(result.receiveInfo)[0].rphone
                    }
                })
            }
        })
    }

    handleSubmit() {
        let commodities = JSON.stringify(
            this.state.cart.map(item => {
                return {
                    id: item.id,
                    quantity: item.quantity,
                    spec: (item.spec) ? item.spec.split('/') : []
                }
            })
        )
        let receiveInfo = JSON.stringify({
            location: this.state.receiver.loc,
            rname: this.state.receiver.name,
            rphone: this.state.receiver.phone
        })
        submitOrder(commodities, receiveInfo)

        localStorage.removeItem('shop-to-submit')
        localStorage.removeItem('cart-to-submit')
    }

    render() {
        return (
            <Fragment>
                <AppBar />
                <div className="container">
                    <ReceiverInfo
                        loc={this.state.receiver.loc}
                        phone={this.state.receiver.phone}
                        name={this.state.receiver.name}
                    />
                    <OrderPanel
                        shop={this.state.shop}
                        cart={this.state.cart}
                        handleSubmit={this.handleSubmit}
                    />
                </div>
            </Fragment>
        );
    }
}